package com.odm.communitymanage.ui.idle

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.util.DrawableUtil
import kotlinx.android.synthetic.main.fragment_idle_list.*
import kotlinx.android.synthetic.main.fragment_ongoing_activities.*


/**
 * @description: 闲置列表页面
 * @author: ODM
 * @date: 2020/4/12
 */
class IdleListFragment : BaseMVVMFragment() {

    //flag 标志 瀑布流是否有被删除item
    var isItemDeleted = false
    private var viewModel : IdleListViewModel ?= null

    private var rvAdapter : IdleAdapter ?= null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProviders.of(this).get(IdleListViewModel::class.java)
        return super.onCreateView(inflater, container, savedInstanceState)
    }


    /**
     * 可见时回调
     * 刷新当前选择tab的数据列表
     */
    override fun onSupportVisible() {
        super.onSupportVisible()
        refreshIdleList(viewModel?.selectedTabIndex)
    }

    override fun initViews() {
        //注册 发布闲置的点击事件
        tvPostIdle.setOnClickListener {
            start(PostIdleFragment())
        }
        //标题返回键点击事件
        btnBackIdleList.setOnClickListener {
            pop()
        }

        initSearchEditText()

        initIdleRecyclerView()

        initTabLayout()

    }

    /**
     * 初始化搜索框的搜索触发点击事件
     */
    private fun initSearchEditText(){
        //
        etSearchIdle.setOnEditorActionListener { v, actionId, event ->
            return@setOnEditorActionListener when (actionId) {

                EditorInfo.IME_ACTION_SEARCH -> {
                    searchActivity()
                    true
                }
                else -> false
            }

        }
        //搜索框的右侧图片点击事件
        val drawRightClick : DrawableUtil = DrawableUtil(etSearchIdle , object : DrawableUtil.OnDrawableListener{
            override fun onLeft(v: View?, left: Drawable?) {
            }
            override fun onRight(v: View?, right: Drawable?) {
                viewModel?.findIdleList(etSearchIdle?.text?.toString() ?: "")
            }
        })
    }
    

    private fun searchActivity(){
        val s = etSearchIdle?.text?.toString()
        if(s != ""){
            hideSoftInput()
            viewModel?.findIdleList(etSearchIdle?.text?.toString() ?: "")
        }else {
            ToastUtils.showShort("搜索内容不可为空")
        }
    }
    


    private fun initIdleRecyclerView(){
        //初始化RecyclerView的配置--设置为瀑布流
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
//        layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE //可防止Item切换
        rvIdleList.layoutManager = layoutManager

        //对RecyclerView设置Adapter
        rvAdapter = IdleAdapter(viewModel?.idleList?.value?.toMutableList() ?: mutableListOf())
//        rvAdapter = IdleAdapter(mutableListOf())
        rvIdleList.adapter = rvAdapter
        rvAdapter?.animationEnable = true
        //设置空布局
        rvAdapter?.setEmptyView(R.layout.layout_empty_list)
        //闲置列表点击事件
        rvAdapter?.setOnItemClickListener { adapter, view, position ->
            LiveEventBus
                .get(Constants.EVENT_IDLE_DETAIL)
                .post(rvAdapter?.data?.get(position))
            start(IdleDetailFragment())
            hideSoftInput()
        }



        rvIdleList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //恢复Glide加载图片
                    Glide.with(this@IdleListFragment).resumeRequests()
                } else {
                    //禁止Glide加载图片
                    Glide.with(this@IdleListFragment).pauseRequests()
                }
            }
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //对RecyclerView中被回收的item进行处理
                if (isItemDeleted) {
                    val lm = recyclerView.layoutManager as StaggeredGridLayoutManager?
                    var firstVisibleItem: IntArray ? = null
                    firstVisibleItem = lm?.findFirstVisibleItemPositions(firstVisibleItem)
                    if (firstVisibleItem != null && firstVisibleItem[0] == 0) {
                        rvIdleList.adapter?.let {
                            isItemDeleted = false
                            it.notifyDataSetChanged()
                        }
                    }
                }
            }
        })
    }


    private fun initTabLayout(){
        //TabLayout点击事件
        tabIdle?.configTabLayoutConfig {
            //选中项的view的回调
            onSelectViewChange = { fromView, selectViewList, reselect ->
                val toView = selectViewList.first()
                if (reselect) {
                    //重复选择
                }
            }
            //选中项index的回调事件--显示不同排序的瀑布流List
            onSelectIndexChange = { fromIndex, selectIndexList, reselect ->
                //toIndex 为 选中 Index
                val toIndex = selectIndexList.first()
                viewModel?.selectedTabIndex  = toIndex
                refreshIdleList(toIndex)
            }
        }
    }

    private fun refreshIdleList(index : Int ?){
        when(index){
            0 -> {
                msv_idle_list?.showLoading()
                viewModel?.getNewestIdleList()
            }
            1 -> {
                msv_idle_list?.showLoading()
                viewModel?.getUpPriceIdleList()
            }
            2 -> {
                msv_idle_list?.showLoading()
                viewModel?.getDownPriceIdleList()
            }
            else -> {}
        }
    }


    override fun initViewModelObserve() {
        viewModel?.apply {
            idleList.observe(this@IdleListFragment , Observer {
                //闲置列表List 对象发生变化，刷新 滚动列表
                it?.let {
                    // 列表数据为空，显示空状态布局
                    // 列表数据不为空根据Adapter数据引用判断使用setList/setDiffNewData
                    if(it.isEmpty()){
                        msv_idle_list?.showEmpty()
                    }else {
                        msv_idle_list?.showContent()
                        if( rvAdapter?.data?.isEmpty() == true ){
                            rvAdapter?.setList(it.toMutableList())
                        }else {
                            rvAdapter?.setDiffNewData(DiffUtil.calculateDiff(IdleAdapter.IdleDiffCallback(rvAdapter?.data?.toList(),it)) , it.toMutableList())
                        }
                    }
                }
            })
        }
    }


    override fun getLayoutId(): Int {
        return R.layout.fragment_idle_list
    }




}